// store/pages/goods/pay.js
const GoodsService = require('../../../services/goods');
const auth = require('../../../utils/auth.js');
const cardService = require('../../../services/card.js');
const userService = require('../../../services/user.js');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        isLoggedIn: false,
        userInfo: null,
        loginReady: false,

        // 订单信息
        orderId: '',
        orderInfo: null,
        payAmount: 0, // 支付金额

        // 云豆相关
        userScore: 0,
        discount: '',
        phone: '',

        // 福利卡相关
        cardList: [],
        cardListWithStatus: [], // 带选中状态的福利卡列表
        selectedCards: [], // 选中的福利卡列表
        useCardScore: 0,
        totalCardScore: 0, // 总福利卡云豆数量
        showAllCards: false, // 是否显示所有卡片
        displayCardCount: 3, // 默认显示卡片数量

        // 支付相关
        useScore: 0,
        remainMoney: 0,
        discount: 0, // 折扣比例
        hasDiscount: false, // 是否有折扣

        // 支付状态
        payRecordId: '',
        payStatus: 0, // 0=未支付，1=已支付
        paymentCompleted: false, // 支付是否已完成

        // UI状态
        loading: false,
        showPayPanel: false,
        showResultPanel: false,

        keyboardHeight: 0,
        colorPalette: [ // 颜色调色板
            '#52c41a', // 绿色
            '#1890ff', // 蓝色
            '#722ed1', // 紫色
            '#fa8c16', // 橙色
            '#13c2c2', // 青色
            '#eb2f96', // 粉色
            '#f5222d', // 红色
            '#faad14', // 黄色
            '#a0d911', // 青柠色
            '#2f54eb'  // 深蓝色
        ],

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // 获取订单ID
        if (options.order_id) {
            this.setData({
                orderId: options.order_id
            });
        }

        // 监听键盘高度变化
        wx.onKeyboardHeightChange(res => {
            this.setData({
                keyboardHeight: res.height + 50
            });
        });

        // 检查登录状态
        this.checkLoginStatus();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        if (this.data.loginReady) {
            this.checkLoginStatus();
        } else if (this.data.isLoggedIn && this.data.orderInfo) {
            // 如果已经登录且有订单信息，重新加载用户余额和福利卡信息
            this.loadUserBalance();
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 检查登录状态
     */
    async checkLoginStatus() {
        try {
            const loginStatus = await auth.checkLoginStatus();
            console.log('检查登录状态:', loginStatus);

            // 如果未登录或未绑定手机号，直接跳转到登录页面
            if (!loginStatus.isLoggedIn || !auth.isValidUserInfo(loginStatus.userInfo)) {
                wx.navigateTo({
                    url: '/pages/index/login'
                });
                return;
            }

            this.setData({
                isLoggedIn: loginStatus.isLoggedIn,
                userInfo: loginStatus.userInfo,
                loginReady: true
            });

            // 获取支付信息
            this.loadPayInfo();
        } catch (error) {
            console.error('检查登录状态失败:', error);
            // 检查失败时也跳转到登录页面
            wx.navigateTo({
                url: '/pages/index/login'
            });
        }
    },

    /**
     * 加载支付信息
     */
    async loadPayInfo() {
        try {
            const result = await GoodsService.getPayInfo(this.data.orderId);

            if (result.success) {
                const payInfo = result.data;

                this.setData({
                    orderInfo: payInfo,
                    payAmount: payInfo.pay_amount,
                    phone: payInfo.phone
                });

                // 加载用户余额和福利卡信息
                this.loadUserBalance();
            } else {
                wx.showToast({
                    title: result.message,
                    icon: 'none'
                });
            }
        } catch (error) {
            console.error('加载支付信息失败:', error);
            wx.showToast({
                title: '获取支付信息失败',
                icon: 'none'
            });
        }
    },

    /**
     * 加载用户云豆余额和福利卡
     */
    async loadUserBalance() {
        try {
            // 加载云豆余额

            const balanceResult = await userService.getBalance({
                showLoading: false
            });

            if (balanceResult.success) {
                if (balanceResult.data.user_card_score_total > 0) {
                    const cardResult = await cardService.getValidCards({
                        showLoading: false
                    });

                    if (cardResult.success) {
                        const validCards = cardResult.data.list || [];
                        const cardListWithStatus = validCards.map(card => ({
                            ...card,
                            isSelected: false,
                            color_index: this.getColorIndex(card.id)
                        }));

                        this.setData({
                            userScore: balanceResult.data.user_score || 0,
                            discount: balanceResult.data.discount || 100,
                            cardList: validCards,
                            cardListWithStatus: cardListWithStatus,
                            totalCardScore: balanceResult.data.user_card_score_total,
                            displayCardCount: validCards.length > 3 ? 3 : validCards.length
                        });
                    }
                } else {
                    this.setData({
                        userScore: balanceResult.data.user_score || 0,
                        discount: balanceResult.data.discount || 100,
                        cardList: [],
                        cardListWithStatus: [],
                        totalCardScore: 0,
                        displayCardCount: 0
                    });
                }
            }

            // 计算支付方案
            this.calculatePayPlan();
        } catch (error) {
            console.error('加载用户余额和福利卡失败:', error);
        }
    },

    /**
     * 选择/取消选择福利卡
     */
    onCardSelect(e) {
        const cardId = e.currentTarget.dataset.id;
        const card = this.data.cardList.find(item => item.id == cardId);

        if (card) {
            const selectedCards = [...this.data.selectedCards];
            const existingIndex = selectedCards.findIndex(item => item.id == cardId);

            if (existingIndex > -1) {
                // 如果已选中，则取消选择
                selectedCards.splice(existingIndex, 1);
            } else {
                // 如果未选中，检查是否可以添加新福利卡
                // 计算当前已选择福利卡的云豆总量
                let currentTotalCardScore = 0;
                for (const selectedCard of selectedCards) {
                    const cardScore = selectedCard.card_score || selectedCard.score || 0;
                    currentTotalCardScore += cardScore;
                }

                // 如果当前已选择的福利卡云豆已经足够支付，则不允许再选择其他福利卡
                if (currentTotalCardScore >= this.data.payAmount) {
                    wx.showToast({
                        title: '已选择的福利卡云豆足够支付，请先取消选择',
                        icon: 'none',
                        duration: 2000
                    });
                    return;
                }

                // 可以添加新福利卡
                selectedCards.push(card);
            }

            // 更新福利卡列表的选中状态
            const cardListWithStatus = this.data.cardListWithStatus.map(item => ({
                ...item,
                isSelected: selectedCards.some(selectedCard => selectedCard.id === item.id)
            }));

            this.setData({
                selectedCards: selectedCards,
                cardListWithStatus: cardListWithStatus,
                paymentCompleted: false // 重置支付完成状态
            });

            // 重新计算支付方案
            this.calculatePayPlan();
        }
    },

    /**
     * 切换显示所有卡片
     */
    toggleShowAllCards() {
        this.setData({
            showAllCards: !this.data.showAllCards,
            displayCardCount: this.data.showAllCards ? 3 : this.data.cardListWithStatus.length
        });
    },

    /**
     * 取消选择所有福利卡
     */
    onCardDeselect() {
        // 更新福利卡列表的选中状态
        const cardListWithStatus = this.data.cardListWithStatus.map(item => ({
            ...item,
            isSelected: false,
            color_index: this.getColorIndex(item.id)
        }));

        this.setData({
            selectedCards: [],
            useCardScore: 0,
            cardListWithStatus: cardListWithStatus,
            paymentCompleted: false // 重置支付完成状态
        });

        // 重新计算支付方案
        this.calculatePayPlan();
    },

    /**
     * 格式化云豆数量显示
     */
    formatScore(score) {
        return parseFloat(score).toFixed(2);
    },

    /**
     * 计算支付方案
     */
    calculatePayPlan() {
        const { payAmount, userScore, selectedCards } = this.data;

        if (!payAmount || payAmount <= 0) return;

        let totalUseScore = 0;
        let totalCardScore = 0;
        let useScore = 0;

        // 1. 先计算用户选择的福利卡云豆使用量（多选）
        if (selectedCards.length > 0) {
            let remainingPayAmount = payAmount;

            // 按福利卡云豆数量从高到低排序，优先使用云豆多的福利卡
            const sortedCards = [...selectedCards].sort((a, b) => {
                const scoreA = a.card_score || a.score || 0;
                const scoreB = b.card_score || b.score || 0;
                return scoreB - scoreA;
            });

            for (const card of sortedCards) {
                const cardScore = card.card_score || card.score || 0;
                if (cardScore > 0 && remainingPayAmount > 0) {
                    const useCardScore = Math.min(cardScore, remainingPayAmount); // 支持小数
                    totalCardScore += useCardScore;
                    totalUseScore += useCardScore;
                    remainingPayAmount -= useCardScore;
                }
            }
        }

        // 2. 然后自动计算云豆使用量（补足剩余金额）
        const remainingMoney = payAmount - totalUseScore;
        if (remainingMoney > 0) {
            const needScore = remainingMoney; // 每个云豆代表1元，支持小数
            useScore = Math.min(userScore, needScore); // 使用的云豆数量
            totalUseScore += useScore;
        }

        // 3. 最后计算微信支付补差价
        const remainMoney = (payAmount - totalUseScore).toFixed(2); // 需要微信支付的金额

        // 4. 计算每个福利卡的选中状态和实际使用云豆数量
        const cardListWithStatus = this.data.cardList.map(card => {
            const isSelected = selectedCards.some(selectedCard => selectedCard.id === card.id);
            let actualUseScore = 0;

            if (isSelected) {
                // 重新计算该福利卡实际使用的云豆数量
                const cardScore = card.card_score || card.score || 0;
                let remainingPayAmount = payAmount;
                let usedCardScore = 0;

                // 按福利卡云豆数量从高到低排序，优先使用云豆多的福利卡
                const sortedSelectedCards = [...selectedCards].sort((a, b) => {
                    const scoreA = a.card_score || a.score || 0;
                    const scoreB = b.card_score || b.score || 0;
                    return scoreB - scoreA;
                });

                // 计算到当前福利卡为止的使用量
                for (const selectedCard of sortedSelectedCards) {
                    if (selectedCard.id === card.id) {
                        // 找到当前福利卡，计算其实际使用量
                        if (cardScore > 0 && remainingPayAmount > 0) {
                            actualUseScore = Math.min(cardScore, remainingPayAmount);
                        }
                        break;
                    } else {
                        // 其他福利卡的使用量
                        const otherCardScore = selectedCard.card_score || selectedCard.score || 0;
                        if (otherCardScore > 0 && remainingPayAmount > 0) {
                            const useOtherCardScore = Math.min(otherCardScore, remainingPayAmount);
                            usedCardScore += useOtherCardScore;
                            remainingPayAmount -= useOtherCardScore;
                        }
                    }
                }
            }

            return {
                ...card,
                isSelected: isSelected,
                color_index: this.getColorIndex(card.id),
                actualUseScore: actualUseScore
            };
        });

        this.setData({
            useScore: useScore,
            useCardScore: totalCardScore,
            remainMoney: remainMoney,
            cardListWithStatus: cardListWithStatus
        });
    },

    /**
     * 开始支付
     */
    async startPay() {
        // 检查支付金额
        if (!this.data.payAmount || this.data.payAmount <= 0) {
            wx.showToast({
                title: '支付金额错误',
                icon: 'none'
            });
            return;
        }

        // 检查订单ID
        if (!this.data.orderId) {
            wx.showToast({
                title: '订单信息错误',
                icon: 'none'
            });
            return;
        }

        // 如果正在加载中，不允许重复点击
        if (this.data.loading) {
            return;
        }

        this.setData({ loading: true });

        try {
            // 准备支付数据
            const payData = {
                order_id: this.data.orderId,
                pay_amount: this.data.payAmount,
                // 云豆余额相关数据
                use_score: this.data.useScore,
                // 福利卡相关数据
                use_card_score: this.data.useCardScore,
                selected_cards: this.data.selectedCards.map(card => {
                    // 从cardListWithStatus中获取该福利卡的实际使用云豆数量
                    const cardWithStatus = this.data.cardListWithStatus.find(item => item.id == card.id);
                    const actualUseScore = cardWithStatus ? cardWithStatus.actualUseScore : 0;

                    return {
                        card_id: card.id,
                        card_name: card.card_name || card.name || '',
                        card_score: card.card_score || card.score || 0,
                        use_score: actualUseScore
                    };
                })
            };

            console.log('提交的支付数据:', payData);

            const result = await GoodsService.createPay(payData);

            console.log('支付API返回结果:', result);

            if (result.success) {
                const payData = result.data;

                this.setData({
                    payRecordId: payData.pay_record_id,
                    payStatus: payData.pay_status,
                    useScore: payData.use_score || this.data.useScore,
                    useCardScore: payData.use_card_score || this.data.useCardScore,
                    remainMoney: payData.remain_money || this.data.remainMoney
                });

                console.log('支付状态更新:', {
                    payStatus: payData.pay_status,
                    remainMoney: payData.remain_money || this.data.remainMoney,
                    useScore: payData.use_score || this.data.useScore,
                    useCardScore: payData.use_card_score || this.data.useCardScore
                });

                // 判断是否需要微信支付
                const needWxPay = (payData.remain_money || this.data.remainMoney) > 0;
                console.log('是否需要微信支付:', needWxPay);

                if (payData.pay_status === 1) {
                    // 支付成功（云豆+福利卡云豆支付完成）
                    const payMessage = this.getPaySuccessMessage();
                    this.setData({
                        paymentCompleted: true
                    });
                    this.showPayResult(true, payMessage);
                } else if (payData.remain_money > 0) {
                    // 需要微信支付补差价
                    this.showPayPanel(payData.wx_pay_config);
                } else if (payData.remain_money <= 0) {
                    // 补差价不大于0，支付完成
                    const payMessage = this.getPaySuccessMessage();
                    this.setData({
                        paymentCompleted: true
                    });
                    this.showPayResult(true, payMessage);
                } else {
                    // 其他情况，也显示支付成功
                    const payMessage = this.getPaySuccessMessage();
                    this.setData({
                        paymentCompleted: true
                    });
                    this.showPayResult(true, payMessage);
                }
            } else {
                wx.showToast({
                    title: result.message,
                    icon: 'none'
                });
            }
        } catch (error) {
            console.error('支付失败:', error);
            wx.showToast({
                title: '支付失败，请重试',
                icon: 'none'
            });
        } finally {
            this.setData({ loading: false });
        }
    },

    /**
     * 获取支付成功消息
     */
    getPaySuccessMessage() {
        const { useScore, useCardScore, payAmount, remainMoney } = this.data;
        let message = '支付成功';

        if (useScore > 0 && useCardScore > 0) {
            message = `福利卡和云豆支付成功，共支付¥${payAmount}`;
        } else if (useCardScore > 0) {
            message = `福利卡支付成功，共支付¥${payAmount}`;
        } else if (useScore > 0) {
            message = `云豆支付成功，共支付¥${payAmount}`;
        } else {
            message = `支付成功，共支付¥${payAmount}`;
        }

        // 如果有微信支付部分，在消息中说明
        if (remainMoney > 0) {
            message += `（含微信支付¥${remainMoney}）`;
        } else {
            message += `（无需微信支付）`;
        }

        return message;
    },

    /**
     * 显示支付面板
     */
    showPayPanel(wxPayConfig) {
        // 确保在显示支付面板时重新计算一次金额
        this.calculatePayPlan();


        this.setData({
            showPayPanel: true,
            wxPayConfig: wxPayConfig
        });
    },

    /**
     * 执行微信支付
     */
    async doWxPay() {
        const { wxPayConfig } = this.data;

        if (!wxPayConfig) {
            wx.showToast({
                title: '支付配置错误',
                icon: 'none'
            });
            return;
        }

        try {
            wx.requestPayment({
                timeStamp: wxPayConfig.timeStamp,
                nonceStr: wxPayConfig.nonceStr,
                package: wxPayConfig.package,
                signType: wxPayConfig.signType,
                paySign: wxPayConfig.paySign,
                success: (res) => {
                    if (res.errMsg === 'requestPayment:ok') {
                        // 支付成功，查询支付状态
                        this.checkPayStatus();
                    } else {
                        wx.showToast({
                            title: '支付失败',
                            icon: 'none'
                        });
                    }
                },
                fail: (res) => {
                    console.error('微信支付失败:', res);
                    wx.showToast({
                        title: '支付失败',
                        icon: 'none'
                    });
                }
            });
        } catch (error) {
            console.error('微信支付异常:', error);
            wx.showToast({
                title: '支付异常',
                icon: 'none'
            });
        }
    },

    /**
     * 检查支付状态
     */
    async checkPayStatus() {
        if (!this.data.payRecordId) return;

        try {
            const result = await GoodsService.queryPayStatus(this.data.payRecordId);

            if (result.success) {
                const payData = result.data;

                this.setData({
                    payStatus: payData.pay_status
                });

                if (payData.pay_status === 1) {
                    this.showPayResult(true, '支付成功');
                } else {
                    // 继续轮询支付状态
                    setTimeout(() => {
                        this.checkPayStatus();
                    }, 2000);
                }
            }
        } catch (error) {
            console.error('查询支付状态失败:', error);
        }
    },

    /**
     * 显示支付结果
     */
    showPayResult(success, message) {
        this.setData({
            showPayPanel: false,
            showResultPanel: true,
            payResult: {
                success: success,
                message: message
            }
        });

        // 支付成功后重新加载用户余额和福利卡信息
        if (success) {
            this.loadUserBalance();
        }
    },

    /**
     * 关闭支付面板
     */
    closePayPanel() {
        this.setData({
            showPayPanel: false
        });
    },

    /**
     * 关闭结果面板
     */
    closeResultPanel() {
        this.setData({
            showResultPanel: false
        });
        console.log(this.data);

        wx.redirectTo({
            url: '/pages/i/order?order_id=' + this.data.orderId
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.loadPayInfo().finally(() => {
            wx.stopPullDownRefresh();
        });
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        return {
            title: '严选商品支付',
            path: '/store/pages/goods/pay'
        };
    },

    /**
     * 根据卡片ID获取固定的颜色索引
     * @param {number} cardId 卡片ID
     * @returns {number} 颜色索引
     */
    getColorIndex(cardId) {
        if (!cardId) return 0;
        // 使用卡片ID的哈希值来确保相同的卡片总是获得相同的颜色
        const hash = this.hashCode(cardId.toString());
        return Math.abs(hash) % this.data.colorPalette.length;
    },

    /**
     * 简单的哈希函数
     * @param {string} str 字符串
     * @returns {number} 哈希值
     */
    hashCode(str) {
        let hash = 0;
        if (str.length === 0) return hash;
        for (let i = 0; i < str.length; i++) {
            const char = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash; // 转换为32位整数
        }
        return hash;
    }
});